var gulp = require('gulp');
var $ = require('gulp-load-plugins')({
  pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
var config = require('./gulp-config');

var sprite = require('css-sprite').stream;

gulp.task('serve', ['env', 'dev-sass'], function() {
  browserSync.init({
    host: '192.168.1.104',
    port: 9000,
    notify: false,
    server: {
      baseDir: ['./src'],
      routes: {
        '/bower-components': 'bower-components'
      }
    }
  });

  gulp.watch([
    config.SRC_PATH_NAME + '*.html',
    config.DEV_SCRIPT_PATH + '**/*.js',
    config.DEV_IMAGE_PATH,
    ]).on('change', reload);

  gulp.watch(config.DEV_STYLE_PATH + '**/*.scss', ['sass-env','dev-sass']);
  gulp.watch(config.DEV_SLICE_PATH + '**/*.*', ['sprite']);
  // gulp.watch('bower.json', ['wiredep']); 

});

gulp.task('clean', function() {
  $.del(['.tmp', 'dist', config.DEV_CSS_PATH]);
});

gulp.task('dev-sass', function() {

  return gulp.src(config.DEV_STYLE_PATH + '**/*.scss')
  .pipe($.sourcemaps.init())
  .pipe($.sass({
    'outputStyle': 'nested',//compressed
    'precision': 10,
    'includePaths': ['.', config.SRC_PATH_NAME],
    'onError': console.error.bind(console, 'Sass error:')
  }))
  .pipe($.autoprefixer({
    browsers: config.CSS_SUPPORT_WEBAPP,
  }))
  .pipe($.if(config.SOURCE_MAP, $.sourcemaps.write()))
  .pipe(gulp.dest(config.DEV_CSS_PATH))
  .pipe(reload({stream: true}));
});

gulp.task('sprite', function() {
  return gulp.src([config.DEV_SLICE_PATH + '**/*.png', 
    config.DEV_SLICE_PATH + '**/*.jpg'])
  .pipe(sprite({
    'name': 'sprite',
    'cssPath': '/images/',
    'orientation': 'binary-tree',
    'template': config.SRC_PATH_NAME + 'util/gem-sprite.mustache',
    'margin': 3,
    'style': '_sprite.scss',
    'processor': 'scss'
  }))
  .pipe($.if('*.png', gulp.dest(config.DEV_IMAGE_PATH), gulp.dest(config.DEV_STYLE_PATH)));
});

gulp.task('env', ['sass-env'], function() {
  // return gulp.src([config.DEV_STYLE_PATH + '**/*.scss'])
  // .pipe($.preprocess({context: {MODE: 'dev'}}))
  // .pipe(gulp.dest(config.TEMP_PATH + 'scss/'));
});


gulp.task('sass-env', function() {
  return gulp.src([config.DEV_STYLE_PATH + 'base/_global.scss'])
  .pipe($.preprocess({context: {MODE: 'dev'}}))
  .pipe($.rename({
    'basename': '_global_',
    'ext': 'scss'
  }))
  .pipe(gulp.dest(config.DEV_STYLE_PATH + 'base/'));
})